package com.nku.mason.masonframework.util;

/**
 * 类型转换工具类
 * @author Mason
 * @date 2017年3月10日
 */
public final class CastUtil {
	
	private CastUtil(){
		//私有构造器，防止外部实例化该对象
	}
	
	/**
	 * 转为String类型
	 * @param obj
	 * @return
	 */
	public static String castString(Object obj){
		return castString(obj,"");
	}
	
	/**
	 * 转为String类型(提供默认值)
	 * @param defaultValue
	 * @return
	 */
	public static String castString(Object obj, String defaultValue){
		return obj != null ? String.valueOf(obj) : defaultValue;
	}
	
	/**
	 * 转为double
	 * @param obj
	 * @return
	 */
	public static double castDouble(Object obj){
		return castDouble(obj, 0);
	}
	
	/**
	 * 转为double(提供默认值)
	 * @param obj
	 * @param defauleValue
	 * @return
	 */
	public static double castDouble(Object obj, double defauleValue){
		
		double val = defauleValue;
		
		if (obj != null) {
			String strVal = castString(obj);
			if (!StringUtil.isEmpty(strVal)) {
				try {
					val = Double.parseDouble(strVal);
				} catch (NumberFormatException e) {
					val = defauleValue;
				}
			}
		}
		
		return val;
	}
	
	/**
	 * 转换为long
	 * @param obj
	 * @return
	 */
	public static long castLong(Object obj){
		return castLong(obj, 0);
	}
	
	/**
	 * 转为long(提供默认值)
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static long castLong(Object obj, long defaultValue){
		long val = defaultValue;
		if (obj != null) {
			String strVal = castString(obj);
			if (!StringUtil.isEmpty(strVal)) {
				try {
					val = Long.parseLong(strVal);
				} catch (NumberFormatException e) {
					val = defaultValue;
				}
			}
		}
		
		return val;
	}
	
	/**
	 * 转为int
	 * @param obj
	 * @return
	 */
	public static int castInt(Object obj){
		return castInt(obj, 0);
	}
	
	/**
	 * 转为int(提供默认值)
	 * @param obj
	 * @param defautValue
	 * @return
	 */
	public static int castInt(Object obj, int defautValue){
		int val = defautValue;
		if (obj != null) {
			String strVal = castString(obj);
			if (!StringUtil.isEmpty(strVal)) {
				try {
					val = Integer.parseInt(strVal);
				} catch (NumberFormatException e) {
					val = defautValue;
				}
			}
		}
		
		return val;
	}
	
	/**
	 * 转为布尔类型
	 * @param obj
	 * @return
	 */
	public static boolean castBoolean(Object obj){
		return castBoolean(obj, false);
	}

	/**
	 * 转为布尔类型(提供默认值)
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static boolean castBoolean(Object obj, boolean defaultValue){
		boolean val = defaultValue;
		if (obj != null) {
			String strVal = castString(obj);
			if (!StringUtil.isEmpty(strVal)) {
				try {
					val = Boolean.parseBoolean(strVal);
				} catch (Exception e) {
					val = defaultValue;
				}
			}
		}
		
		return val;
	}
}






















